package org.lwd.datalink.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.lwd.datalink.domain.task.TaskShadowInfo;
import org.lwd.datalink.mapper.TaskShadowMapper;
import org.lwd.datalink.service.TaskShadowService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 影子任务 Service 接口
 *
 * @Author: weidong.lin
 * @Date: create in 2024/4/2 14:06
 */
@Slf4j
@Service
public class TaskShadowServiceImpl implements TaskShadowService {

    @Resource
    private TaskShadowMapper taskShadowMapper;

    @Override
    public TaskShadowInfo getExecutingTaskShadow(Long taskId) {
        return taskShadowMapper.getTaskShadowInExecutingState(taskId);
    }

    @Override
    public TaskShadowInfo takeOneTaskShadow(Long taskId) {
        return taskShadowMapper.getMinTaskShadowInInitState(taskId);
    }

    @Override
    public void startTaskShadow(TaskShadowInfo taskShadowInfo) {
        if (TaskShadowInfo.State.INIT.equals(taskShadowInfo.getState())) {
            taskShadowInfo.setState(TaskShadowInfo.State.EXECUTING);
            taskShadowMapper.updateTaskShadowState(taskShadowInfo);
        } else {
            throw new IllegalStateException("start task shadow failed for the current state is not INIT.");
        }
        log.info("Task Shadow {} started.", taskShadowInfo.getId());
    }

    @Override
    public void completeTaskShadow(TaskShadowInfo taskShadowInfo) {
        if (TaskShadowInfo.State.EXECUTING.equals(taskShadowInfo.getState())) {
            taskShadowInfo.setState(TaskShadowInfo.State.COMPLETE);
            taskShadowMapper.updateTaskShadowState(taskShadowInfo);
        } else {
            throw new IllegalStateException("complete task shadow failed for the current state is not EXECUTING.");
        }
        log.info("Task Shadow {} completed.", taskShadowInfo.getId());
    }

    @Override
    public boolean discardTaskShadow(Long id) {
        boolean result = taskShadowMapper.discardTaskShadow(id) > 0;
        log.info("Task Shadow {} discarded.", id);
        return result;
    }
}
